<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>获取元素的祖先元素</title>
</head>

<body>
    <header>
        <nav></nav>
    </header>
    <main id="content"></main>
</body>
<script>
    const getAncestors = el => {
        const ancestors = [];
        while (el) {
            ancestors.unshift(el);
            el = el.parentNode;
        }
        return ancestors;
    }
    const elements = getAncestors(document.querySelector('nav'))
    console.log(elements)
    document.querySelector("#content").innerHTML = JSON.stringify(elements.map(item => item.nodeName.toLowerCase().replace(/#/g,"")))
</script>

</html>